/*
 * $Id: dbserver.prg 2012-09-17 14:53 riztan $
 */

#include "hbclass.ch"
#include "common.ch"
#include "dbstruct.ch"
#include "xhb.ch"
#include "tdolphin.ch"

#define CRLF  hb_eol()
#define MSG_LINE  hb_eol()+Repl("-",30)

CLASS TAPP FROM TPUBLIC
   DATA cConnDefault   INIT ""

   METHOD SetDefault( oConn )  INLINE ::cConnDefault := oConn:cConnName

ENDCLASS




CLASS DBSERVER FROM TApp

   CLASSDATA oConnections

   DATA cConnDefault
   //DATA aConnTypes    INIT {"pgsql","mysql"}
   DATA aQueries      INIT {}
   DATA oConnections
   
   METHOD New( cConnName, cIniName, ... )
//   METHOD SetDefault( oParent )  INLINE  oParent:cConnDefault := ::cConnType

   METHOD GetConnect( cConnName, cIniName, ... )

//   METHOD ConnRegis(  )  AADD( ::oConnections, self )

   METHOD Connect( cIniName )

   METHOD Info( cConn )

   METHOD GetConn( cConn )

   METHOD Query( cQuery )

   METHOD ModelQuery( xQuery )

   METHOD Destroy(cConn)

ENDCLASS


METHOD NEW( cConnName, cIniName, ... ) CLASS DbServer
   Local oConn

   ::cConnDefault := ""
   ::oConnections := TPublic():New()

   if PCount() > 1

      ? MSG_LINE
      oConn := ::GetConnect( cConnName, cIniName, ... )
      ::cConnDefault := cConnName
      ? "Registrada Conexion ["+cConnName+"] en oApp:Server:oConnections. "
      ? MSG_LINE

   endif
Return self



/** \brief 
Crea una conexión y la registra en el objeto de control. */
METHOD GETCONNECT( cConnName, cIniName, ... ) CLASS DbServer
   local cText
   local lResp
   local oSrv
   Local oTemp:=nil


   //::oConnections:Add( cConnName, ::Connect( cIniName ) )

   //oSrv := ::oConnections:Get( cConnName )
   oSrv := ::Connect( cIniName )
   
   If hb_ISNIL( oSrv )
      ? "No puede conectar con el servicio [" + cIniName + "]"
      Return nil
   Else
      If !oSrv:lError
      
         lResp := .t.
      
         ? "Creado Objeto ["+cConnName+"] "

         cText := "Connection OK" + CRLF
         cText += "Host: " + oSrv:cHost +CRLF
//         cText += "Database: " +oDbServer:cDBName + CRLF

//         ? oDbServer:Query( "select * from test")
//         ? oDbServer:query( "select get_lock('2',180 )" )
//         ? oDbServer:query( "select release_lock('2')" )
         ? cText
         

         ::oConnections:Add( cConnName, Tpublic():New() )
         oTemp := ::oConnections:Get( cConnName )
         oTemp:cIniName := cIniName
         oTemp:cDBType  := "falta colocar..." 
         oTemp:cClass   := oSrv:ClassName() 
         oTemp:oConn    := oSrv 
         oTemp:lAutoAdd := .f.
         ? "Registrada Conexion ["+cConnName+"] en oApp:Server:oConnections. "
         
         Return Self //oSrv
         
      EndIf

   EndIf

RETURN nil




/** \brief Crea el objeto de conexion con el servidor indicado.
    \return Devuelve el objeto si realizó la conexión. Caso contrario 
     devuelve nulo.
 */
METHOD Connect( cIniName )
   LOCAL c 
   LOCAL hIni      
   LOCAL oServer:=NIL
   LOCAL cDbType,cHost, cUser, cPassword, nPort, cDBName,nFlags,cSchema    
   LOCAL oErr

   default cIniName to "tpy_mysql"

   ? "Conectando configuracion [" + cIniName +"] en fichero .ini "

   hIni      := HB_ReadIni( "connect.ini" )
   oServer   := NIL
   cDBType   := hIni[ cIniName ]["srv"]
   cHost     := hIni[ cIniName ]["host"]
   cUser     := hIni[ cIniName ]["user"]
   cPassword := hIni[ cIniName ]["psw"]
   nPort     := val(hIni[ cIniName ]["port"])
   cDBName   := hIni[ cIniName ]["dbname"]
//   nFlags    := val(hIni[ cIniName ]["flags"])

   TRY
      if cDBType == "mysql"
         CONNECT oServer HOST cHost ;
                         USER cUser ;
                         PASSWORD cPassword ;
                         PORT nPort ;
                         FLAGS val(hIni[ cIniName ]["flags"]) ;
                         DATABASE cDBName

      elseif cDBType == "pgsql"
         oServer := TPQServer():New( cHost,     ;
                                     cDBName,   ; 
                                     cUser,     ;
                                     cPassword, ;
                                     nPort,     ;
                                     hIni[cIniName]["schema"] )
      endif

                                
   CATCH oErr 
     RETURN NIL
   END
   
RETURN oServer


/** \brief Devuelve un texto con información de la conexión predeterminada o
     la que se indique con <i>cConn</i>
 */
METHOD INFO( cConn ) CLASS DbServer
   local oConn
   local cText

   oConn := ::GetConn( cConn )
   if !hb_IsObject( oConn )
      return nil
   endif
   
   cText := "DB Engine: " + oConn:cDbType + hb_eol()
   cText += "Class Name: " + oConn:cClass
return cText


/** \brief Devuelve el objeto correspondiente a la conexion predeterminada o
  la indicada en <i>cConn</i>
 */
METHOD GETCONN( cConn ) CLASS DbServer

   default cConn to ::cConnDefault

   if !::oConnections:IsDef( cConn ) 
      return nil 
   endif
RETURN ::oConnections:Get(cConn)




METHOD QUERY( cQuery, cConn, aError ) CLASS DbServer
   local oConn
   local oQry

   default cConn to ::cConnDefault
   default aError to Array(2)

   oConn := ::GetConn( cConn ):oConn

   if !hb_IsObject( oConn ) 
      aError[1] := 1
      aError[2] := "Conexion Indefinida"
      return nil 
   endif

   try 
      oQry := oConn:Query( cQuery )
   catch
      aError[1] := 2
      aError[2] := "Problema al Crear la Consulta."
      Return nil
   end

/* RIGC - aqui registrar el query */

RETURN oQry


METHOD MODELQUERY( xQry, cConn )
   local oQry
   local oDbModel
   local oLin

   if ValType(xQry) ; oQry := ::Query( xQry, cConn ) ; endif

   if !hb_IsObject( oQry ) ; return nil ; endif

   oDbModel := TPublic():New()
   
   FOR EACH oLin IN oQry:aStruct
   NEXT
   //oDbModel 

RETURN oDbModel


/** \brief Cierra la conexión y la borra del objeto de control. */
METHOD DESTROY(cConn) CLASS DbServer
   if !::IsDef(cConn)
      Return .f.
   endif
   ::Get(cConn):End()
   ::Del(cConn)
RETURN .t.



//eof
